package gugga.tasks
{
	import flash.events.EventDispatcher;
	
	import gugga.tasks.events.TaskEvent;
	import gugga.utils.DoLaterUtil;

	[Event(name="start", type="TaskEvent")]
	[Event(name="interrupted", type="TaskEvent")]
	[Event(name="completed", type="TaskEvent")]
	
	/**
	 * <code>FrameWaitingTask</code> is a task that completes when the specified number of 
	 * frames have been elapsed.
	 */
	public class FrameWaitingTask extends EventDispatcher implements ITask
	{
		private var mIsRunning : Boolean = false;
		private var mFramesDelay : Number;
		
		public function FrameWaitingTask(aFramesDelay:Number) 
		{
			super();
			mFramesDelay = aFramesDelay;
		}
	
		public function start() : void 
		{
			mIsRunning = true;
			dispatchEvent(new TaskEvent(TaskEvent.START));
			
			if(mFramesDelay > 0)
			{
				DoLaterUtil.doLater(onCompleted, null, mFramesDelay, this);
			}
			else
			{
				onCompleted();
			}
		}
		
		private function onCompleted() : void
		{
			if(mIsRunning)
			{
				mIsRunning = false;
				dispatchEvent(new TaskEvent(TaskEvent.COMPLETED));
			}
		}
	
		public function isRunning() : Boolean 
		{
			return mIsRunning;
		}
	
		public function isImmediatelyInterruptable() : Boolean 
		{
			return true;
		}
	
		public function interrupt() : void 
		{
			mIsRunning = false;
			dispatchEvent(new TaskEvent(TaskEvent.INTERRUPTED));
		}
	}
}